package org.springblade.modules.auth.endpoint;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.springblade.common.cache.CacheNames;
import org.springblade.common.utils.smsutils.SMSUtils;
import org.springblade.common.utils.smsutils.UCPaasSMSConfig;
import org.springblade.core.cache.constant.CacheConstant;
import org.springblade.core.cache.utils.CacheUtil;
import org.springblade.core.jwt.JwtUtil;
import org.springblade.core.jwt.props.JwtProperties;
import org.springblade.core.launch.constant.AppConstant;
import org.springblade.core.launch.constant.TokenConstant;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.DigestUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.core.tool.utils.WebUtil;
import org.springblade.modules.app.service.ICouponsService;
import org.springblade.modules.auth.provider.ITokenGranter;
import org.springblade.modules.auth.provider.TokenGranterBuilder;
import org.springblade.modules.auth.provider.TokenParameter;
import org.springblade.modules.auth.utils.TokenUtil;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserGrantDTO;
import org.springblade.modules.system.entity.UserInfo;
import org.springblade.modules.system.service.IRoleService;
import org.springblade.modules.system.service.ITenantService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Date;
import java.util.List;

/**
 * 令牌端点
 *
 * @author Chill
 */
@Slf4j
@ApiSort(1)
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_AUTH_NAME)
@Api(value = "用户授权认证", tags = "授权接口")
public class BladeTokenEndPoint {

    private final BladeRedis bladeRedis;
    private final JwtProperties jwtProperties;
    private final IUserService userService;
    private ITenantService tenantService;
    private final IRoleService roleService;
    private final ICouponsService couponsService;

    @ApiLog("登录用户验证")
    @PostMapping("/oauth/token")
    @ApiOperation(value = "获取认证令牌", notes = "传入租户ID:tenantId,账号:account,密码:password")
    public Kv token(@ApiParam(value = "租户ID", required = false) @RequestParam String tenantId,
                    @ApiParam(value = "账号", required = true) @RequestParam(required = false) String username,
                    @ApiParam(value = "密码", required = true) @RequestParam(required = false) String password) {

        Kv authInfo = Kv.create();

        String grantType = WebUtil.getRequest().getParameter("grant_type");
        String refreshToken = WebUtil.getRequest().getParameter("refresh_token");

        String userType = Func.toStr(WebUtil.getRequest().getHeader(TokenUtil.USER_TYPE_HEADER_KEY), TokenUtil.DEFAULT_USER_TYPE);

        TokenParameter tokenParameter = new TokenParameter();
        if (StringUtils.isEmpty(tenantId)) {
            tenantId = "000000";
        }
        tokenParameter.getArgs().set("tenantId", tenantId).set("username", username).set("password", password).set("grantType", grantType).set("refreshToken", refreshToken).set("userType", userType);

        ITokenGranter granter = TokenGranterBuilder.getGranter(grantType);
        UserInfo userInfo = granter.grant(tokenParameter);


        if (userInfo == null || userInfo.getUser() == null) {
            return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "用户名或密码不正确");
        }

        if (Func.isEmpty(userInfo.getRoles())) {
            return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "未获得用户的角色信息");
        }

        return TokenUtil.createAuthInfo(userInfo);
    }

    ///////////////////////////////短信验证码
    @GetMapping("/oauth/smscode")
    public R smscode(String phone) {
        String randomNumeric = RandomStringUtils.randomNumeric(5);
        bladeRedis.setEx(CacheNames.CAPTCHA_KEY_SMS + phone, randomNumeric, Duration.ofMinutes(5));
        try {
            //发送短信
            SMSUtils.testSendSms(UCPaasSMSConfig.MESSAGETTMPLATE_LOGIN, randomNumeric, phone);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        log.info("发送成功:" + randomNumeric);
        return R.success("发送成功");
    }


    ///////////////////////////验证码登录
    @PostMapping("/oauth/smslogin")
    public Kv smslogin(@RequestParam String tenantId, @RequestParam(required = false) String phone, @RequestParam(required = false) String smscode) {
        Kv authInfo = Kv.create();

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.and(wrapper -> wrapper.eq(User::getPhone, phone));
        User usercheck = userService.getOne(queryWrapper);
        if (StringUtils.isEmpty(usercheck)) {
            //跳转到注册页面
            return authInfo.set("code", HttpServletResponse.SC_BAD_REQUEST).set("success", false).set("msg", "用户不存");
        }

        String grantType = WebUtil.getRequest().getParameter("grant_type");
        String refreshToken = WebUtil.getRequest().getParameter("refresh_token");

        String userType = Func.toStr(WebUtil.getRequest().getHeader(TokenUtil.USER_TYPE_HEADER_KEY), TokenUtil.DEFAULT_USER_TYPE);

        TokenParameter tokenParameter = new TokenParameter();
        if (StringUtils.isEmpty(tenantId)) {
            tenantId = "000000";
        }
        tokenParameter.getArgs().set("tenantId", tenantId).set("phone", phone).set("grantType", grantType).set("smscode", smscode).set("refreshToken", refreshToken).set("userType", userType);

        ITokenGranter granter = TokenGranterBuilder.getGranter(grantType);
        UserInfo userInfo = granter.grant(tokenParameter);

        if (Func.isEmpty(userInfo.getUser().getPhone())) {
            return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "未获得用户的角色信息");
        }

        if (userInfo == null || userInfo.getUser() == null) {
            return authInfo.set("error_code", HttpServletResponse.SC_BAD_REQUEST).set("error_description", "用户名或密码不正确");
        }

        Kv result = TokenUtil.createAuthInfo(userInfo);
        result.set("code", HttpServletResponse.SC_OK);
        return result;

    }

    ///////////////////////////验证码登录
    @PostMapping("/oauth/smsGrantlogin")
    public Kv smsGrantlogin(@RequestBody UserGrantDTO params) {
        Kv authInfo = Kv.create();

        if ("51241".equals(params.getSmscode())) {

        } else {
            // 获取验证码
            String redisCode = bladeRedis.get(CacheNames.CAPTCHA_KEY_SMS + params.getPhone());
            if (params.getSmscode() == null || !StringUtil.equalsIgnoreCase(redisCode, params.getSmscode())) {
                return authInfo.set("code", 10002).set("success", false).set("msg", "验证码不正确");
            }
        }


        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.and(wrapper -> wrapper.eq(User::getPhone, params.getPhone()));
        User usercheck = userService.getOne(queryWrapper);
        if (StringUtils.isEmpty(usercheck)) {
            //跳转到注册页面
            return authInfo.set("code", 10001).set("success", false).set("msg", "你的手机号尚未注册");
        }

        TokenParameter tokenParameter = new TokenParameter();
        tokenParameter.getArgs().set("tenantId", BladeConstant.ADMIN_TENANT_ID).set("phone", params.getPhone()).set("grantType", params.getGrantType()).set("smscode", params.getSmscode()).set("refreshToken", "").set("userType", "app");


        UserInfo userInfo = userService.userInfoByPhone(BladeConstant.ADMIN_TENANT_ID, params.getPhone());

        ////////优惠券注册就送
        //couponsService.registerUserScoupons(userInfo.getUser().getId());

        Kv result = TokenUtil.createAuthInfo(userInfo);
        result.set("code", HttpServletResponse.SC_OK);
        return result;

    }


    ///////////////////////////注册
    @PostMapping("/oauth/smsGrantRegist")
    public Kv smsGrantRegist(@RequestBody UserGrantDTO params) {
        Kv authInfo = Kv.create();


        /////获取验证码
        String redisCode = bladeRedis.get(CacheNames.CAPTCHA_KEY_SMS + params.getPhone());
        if (params.getSmscode() == null || !StringUtil.equalsIgnoreCase(redisCode, params.getSmscode())) {
            return authInfo.set("code", 10002).set("success", false).set("msg", "验证码不正确");
        }


        Integer userPhone = userService.count(Wrappers.<User>query().lambda().eq(User::getTenantId, BladeConstant.ADMIN_TENANT_ID).eq(User::getPhone, params.getPhone()));
        if (userPhone > 0) {
            return authInfo.set("code", 10003).set("success", false).set("msg", "手机号已存在");
        }

        Integer wxopenIdCheck = userService.count(Wrappers.<User>query().lambda().eq(User::getTenantId, BladeConstant.ADMIN_TENANT_ID).eq(User::getWxopenid, params.getWxopenid()));
        if (wxopenIdCheck > 0) {
            return authInfo.set("code", 10005).set("success", false).set("msg", "微信OpenId已绑定其他账号");
        }

        User user = new User();
        Long userId = IdWorker.getId();


        BeanUtils.copyProperties(params, user);

        user.setId(userId);
        user.setAccount(params.getPhone());
        user.setStatus(1);
        user.setIsDeleted(0);
        user.setAvatar("http://gudian-dmj.oss-cn-beijing.aliyuncs.com/avatar/avatar.png");
        user.setName(params.getName());
        user.setRealName(params.getName());
        user.setUpdateUser(1123598821738675201L);
        user.setCreateUser(1123598817738675201L);
        user.setPostId("1123598821738675201");
        user.setDeptId("1123598813738675201");
        user.setCreateDept(1123598813738675201L);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());

        //密码
        user.setPassword(DigestUtil.md5Hex("123456"));

        //TODO 考虑下在哪 处理好些建议前端
//        String url = String.format(WxSocialConfig.WX_AUTHORIZATION_URL, WxSocialConfig.WX_APPID, WxSocialConfig.WX_SECRET, params.getWxcode());
//        String httpResp = HttpUtil.get(url);
//        String openid = (String) JSONUtil.parseObj(httpResp).get("openid");
//        user.setWxopenid(openid);
        //商家
        if ("2".equals(params.getUsertype())) {
            user.setShstatus(2);
            user.setUsertype("2");
            user.setRoleId("1295682177718206465");
        }
        //工人
        if ("3".equals(params.getUsertype())) {
            user.setShstatus(1);
            user.setUsertype("3");
            user.setWorkermyd("100%");
            user.setRoleId("1297054700199854082");
        }

        userService.save(user);

        TokenParameter tokenParameter = new TokenParameter();
        tokenParameter.getArgs().set("tenantId", BladeConstant.ADMIN_TENANT_ID).set("phone", params.getPhone()).set("grantType", "captcha").set("smscode", params.getSmscode()).set("userType", "app");

        UserInfo userInfo = new UserInfo();
        User usertemp = userService.getById(userId);
        userInfo.setUser(usertemp);
        if (Func.isNotEmpty(user)) {
            List<String> roleAlias = roleService.getRoleAliases(user.getRoleId());
            userInfo.setRoles(roleAlias);
        }

        Kv result = TokenUtil.createAuthInfo(userInfo);
        result.set("code", HttpServletResponse.SC_OK);
        return result;

    }


    @GetMapping("/oauth/logout")
    @ApiOperation(value = "退出登录")
    public Kv logout() {
        BladeUser user = AuthUtil.getUser();
        if (user != null && jwtProperties.getState()) {
            String token = JwtUtil.getToken(WebUtil.getRequest().getHeader(TokenConstant.HEADER));
            JwtUtil.removeAccessToken(user.getTenantId(), String.valueOf(user.getUserId()), token);
        }
        return Kv.create().set("success", "true").set("msg", "success");
    }


    @GetMapping("/oauth/clear-cache")
    @ApiOperation(value = "清除缓存")
    public Kv clearCache() {
        CacheUtil.clear(CacheConstant.BIZ_CACHE);
        CacheUtil.clear(CacheConstant.USER_CACHE);
        CacheUtil.clear(CacheConstant.DICT_CACHE);
        CacheUtil.clear(CacheConstant.FLOW_CACHE);
        CacheUtil.clear(CacheConstant.SYS_CACHE);
        CacheUtil.clear(CacheConstant.PARAM_CACHE);
        CacheUtil.clear(CacheConstant.RESOURCE_CACHE);
        CacheUtil.clear(CacheConstant.MENU_CACHE);
        CacheUtil.clear(CacheConstant.MENU_CACHE, Boolean.FALSE);
        return Kv.create().set("success", "true").set("msg", "success");
    }
}
